
package com.zcp.pcsuitall;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class WifiActivity extends Activity implements ActivityInterface {
    private static final String TAG = "WifiActivity";

    private int openSocketByWifi = 1001;

    private TextView title;

    private TextView ipTextView;

    private Button wifiOper;

    private String noWifiInfo;

    private String WifiInfo;

    private String closeWiFi;

    private String settingWifi;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.wifi);
        title = (TextView) findViewById(R.id.textViewWifiTitle);
        ipTextView = (TextView) findViewById(R.id.textViewIP);
        wifiOper = (Button) findViewById(R.id.buttonWifi);
        noWifiInfo = getString(R.string.please_con_wifi);
        WifiInfo = getString(R.string.coning_wifi);
        closeWiFi = getString(R.string.close_wifi);
        settingWifi = getString(R.string.setting_wifi);

        // 注册监听广播服务
        IntentReceiver.register(this);
        wifiOper.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                buttonOnClick();
            }
        });
//        Log.e("222", "1111111111111111111111111111111111111111111111WifiActivity start"+ipTextView);
        restartServiceByWifi();
    }

    @Override
    protected void onStart() {
        super.onStart();
//        Log.e("222", "3333333333333333333333333333333333333333333333333333WifiActivity start"+ipTextView);
       
       
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Log.i("222", "333333333333333333333333333333333333333333333333333333333333333333onActivityResult=" + requestCode);
        if (requestCode == openSocketByWifi) {
            restartServiceByWifi();
        }
    }

    private void buttonOnClick() {
        String state=wifiOper.getText().toString();
        
        //处于关闭文字
        if (closeWiFi.equals(state)) {
            stopService();
            Intent intent = new Intent(this, PhoneServiceAllActivity.class);
            startActivity(intent);
            finish();
        } else {
//            if (!SuitUtil.isWifiEnable(this)) {
                SuitUtil.openWifiSetting(this, openSocketByWifi);
//            }
        }
    }

    /**
     * 通过wifi的ip重启服务
     */
    private void restartServiceByWifi() {
        // Log.e("222", "restartServiceByWifi");
        if (SuitUtil.isWifiEnable(this)) {
            title.setText(WifiInfo);
            title.setTextColor(this.getResources().getColor(R.color.black));
            String ip = SuitUtil.getLocalIpAddress();
            // Log.e("222", "restartServiceByWifi=" + ip);
            stopService();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String cipherKey = MyDes.getRandomStr(2);
            String show = SuitUtil.getVerificationCode(ip) + cipherKey;
            startService(ip, show.substring(2));
            ipTextView.setText(show);
            wifiOper.setText(closeWiFi);
        } else {
            title.setText(noWifiInfo);
            title.setTextColor(this.getResources().getColor(R.color.red));
            wifiOper.setText(settingWifi);
        }
    }

    /**
     * 启动socket服务连接。<br>
     * 
     * @param context
     */
    private void startService(String ip, String cipherKey) {

        SharedPreferences shPre = getSharedPreferences("PcSuitPhone", Context.MODE_PRIVATE);
        if (shPre.getString("haveStartSocket", "notSet").equals("ok")) {
            return;
        }
        Intent startIntent = new Intent(this, SocketService.class);
        Bundle startBundle = new Bundle();

        startBundle.putInt("server_port", 8849);// 默认socket端口
        startBundle.putString("ip", ip);
        startBundle.putString("class", "WifiActivity");
        startBundle.putString("cipherKey", cipherKey);
        startIntent.putExtras(startBundle);
        startService(startIntent);

        Editor editor = shPre.edit();
        editor.putString("haveStartSocket", "ok");
        // 取密钥最后两位作为识别码
        int len = cipherKey.length();
        editor.putString("cipherKey", cipherKey.substring(len - 2));
        editor.commit();

    }

    /**
     * 停止socket服务。
     * 
     * @param context
     */
    private void stopService() {
        try {
            Intent stopIntent = new Intent(this, SocketService.class);
            stopService(stopIntent);

            SharedPreferences shPre = getSharedPreferences("PcSuitPhone", Context.MODE_PRIVATE);
            Editor editor = shPre.edit();
            editor.putString("haveStartSocket", "not");
            editor.commit();
            // cancelNotifyIcon();
            Log.i(TAG, "onReceive stopService");
        } catch (Exception e) {
            Log.e(TAG, "stopService error" + e.getMessage());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            checkExist();
        }
        return true;
    }

    @Override
    public void stopActivity(String stopKey) {
        stopService();
        this.finish();
    }

    @Override
    protected void onDestroy() {
        IntentReceiver.unRegister(this);
        super.onDestroy();
    }

    /**
     * 退出前检查一下。
     * 
     * @return
     */
    private void checkExist() {
        AlertDialog.Builder builder = new Builder(this);
        builder.setMessage(this.getString(R.string.exist));
        builder.setTitle(this.getString(R.string.Confirm));
        builder.setPositiveButton(this.getString(R.string.ok),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        stopService();
                        finish();
                    }
                });

        builder.setNegativeButton(this.getString(R.string.cancel),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }
}
